package com.boot.config;

import com.boot.common.CodeMap;
import com.boot.common.SDataResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xuxiaobao on 2017/8/9.
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    /**
     * 参数校验,拦截@Validated验证的参数错误信息
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Object testValid(HttpServletRequest request,
                          MethodArgumentNotValidException ex) {
        List<Map<Object, Object>> errors = new ArrayList<>();
        for (FieldError item : ex.getBindingResult().getFieldErrors()) {
            Map<Object, Object> map = new HashMap<>();
            map.put("field", item.getField());
            map.put("message", item.getDefaultMessage());
            errors.add(map);
        }
        return new SDataResult(CodeMap.PARAMETER_ERROR,errors);
    }
}
